package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdComModule;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.vo.MdComModuleVo;
import com.gqj.meter.mapper.MdInTaskDetailsMapper;
import com.gqj.meter.service.IMdComModuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 通讯模块Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdComModule", description = "通讯模块")
@RestController
@RequestMapping("/meter/mdComModule")
public class MdComModuleController extends BaseController {
    @Autowired
    private IMdComModuleService mdComModuleService;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;

    /**
     * 查询通讯模块列表
     */
    @ApiOperation("查询通讯模块列表")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdComModule mdComModule) {
        startPage();
        List<MdComModule> list = mdComModuleService.selectMdComModuleList(mdComModule);
        return getDataTable(list);
    }

    /**
     * 导出通讯模块列表
     */
    @ApiOperation("导出通讯模块列表")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:export')")
    @Log(title = "通讯模块", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdComModule mdComModule) {
        List<MdComModule> list = mdComModuleService.selectMdComModuleList(mdComModule);
        ExcelUtil<MdComModule> util = new ExcelUtil<MdComModule>(MdComModule.class);
        util.exportExcel(response, list, "通讯模块数据");
    }

    /**
     * 获取通讯模块详细信息
     */
    @ApiOperation("获取通讯模块详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:query')")
    @GetMapping(value = "/{moduleId}")
    public AjaxResult getInfo(@PathVariable("moduleId") Long moduleId) {
        return success(mdComModuleService.selectMdComModuleByModuleId(moduleId));
    }

    /**
     * 新增通讯模块
     */
    @ApiOperation("新增通讯模块")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:add')")
    @Log(title = "通讯模块", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdComModule mdComModule) {
        if (UserConstants.NOT_UNIQUE.equals(mdComModuleService.checkRfidNoUnique(mdComModule))) {
            return AjaxResult.error("新增'" + mdComModule.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdComModuleService.insertMdComModule(mdComModule));
    }

    /**
     * 修改通讯模块
     */
    @ApiOperation("修改通讯模块")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:edit')")
    @Log(title = "通讯模块", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdComModule mdComModule) {
        if (null == mdComModule.getModuleId() || 0 == mdComModule.getModuleId()) {
            return AjaxResult.error("修改失败，通讯模块ID为空！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdComModuleService.checkRfidNoUnique(mdComModule))) {
            return AjaxResult.error("修改'" + mdComModule.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdComModuleService.updateMdComModule(mdComModule));
    }

    /**
     * 删除通讯模块
     */
    @ApiOperation("删除通讯模块")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:remove')")
    @Log(title = "通讯模块", businessType = BusinessType.DELETE)
    @DeleteMapping("/{moduleIds}")
    public AjaxResult remove(@PathVariable Long[] moduleIds) {
        //判断通讯模块是否被引用
        for (int i = 0; i < moduleIds.length; i++) {
            MdComModule mdComModule = mdComModuleService.selectMdComModuleByModuleId(moduleIds[i]);
            //查看盘点单是否引用
            String serviceStatus = mdComModule.getServiceStatus();
            if (!"00".equals(serviceStatus) && !"01".equals(serviceStatus) && !"04".equals(serviceStatus)) {
                return AjaxResult.error("模块" + mdComModule.getRfidNo() + "的业务状态不允许删除！");
            }

            //查看出入库是否引用
            MdInTaskDetails mdInTaskDetails = new MdInTaskDetails();
            mdInTaskDetails.setRfidNo(mdComModule.getRfidNo());
            mdInTaskDetails.setIsComplete("0");
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(mdInTaskDetails);
            if (mdInTaskDetailsList.size() > 0) {
                return AjaxResult.error("模块" + mdComModule.getRfidNo() + "入库任务中已经引用，无法删除！");
            }
        }
        return toAjax(mdComModuleService.deleteMdComModuleByModuleIds(moduleIds));
    }

    /**
     * 下载通讯模块json文件
     */
    @ApiOperation("下载通讯模块json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:downloadJsonMdComModule')")
    @GetMapping("/downloadJsonMdComModule")
    public AjaxResult downloadJsonMdComModule(MdComModule mdComModule) {
        List<MdComModule> cms = mdComModuleService.selectMdComModuleList(mdComModule);
        List<MdComModuleVo> vos = StorageUtil.copyList(cms, MdComModuleVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "通讯模块数据" + orderNo);
        return AjaxResult.success(fileName + "通讯模块数据" + orderNo);
    }

    /**
     * 导入通讯模块execl文件
     */
    @ApiOperation("导入通讯模块execl文件")
    @Log(title = "导入通讯模块execl文件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:importDataComModule')")
    @PostMapping("/importDataComModule")
    public AjaxResult importDataComModule(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MdComModule> util = new ExcelUtil<MdComModule>(MdComModule.class);
        List<MdComModule> comModuleList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mdComModuleService.importComModule(comModuleList, updateSupport, operName);
        return success(message);
    }

    @ApiOperation("下载通讯模块模板")
    @PostMapping("/importTemplateMdComModule")
    @PreAuthorize("@ss.hasPermi('meter:mdComModule:importTemplateMdComModule')")
    public void importTemplateMdComModule(HttpServletResponse response) {
        ExcelUtil<MdComModule> util = new ExcelUtil<MdComModule>(MdComModule.class);
        util.importTemplateExcel(response, "通讯模块数据");
    }
}
